CC			= g++
DLLTOOL		= dlltool
RM			= bin/linux/rm
MKDIR   	= bin/linux/mkdir
TR 			= bin/linux/tr
DIRNAME		= bin/linux/dirname
ECHO		= echo
GIT  		= git

ifeq ($(OS), Windows_NT)
    ifeq ($(PROCESSOR_ARCHITEW6432), AMD64)
        ARCH := amd64
    else
        ifeq ($(PROCESSOR_ARCHITECTURE), AMD64)
            ARCH := amd64
        endif
        ifeq ($(PROCESSOR_ARCHITECTURE), x86)
            ARCH := ia32
        endif
    endif
else
	UNAME_P := $(shell uname -p)
    ifeq ($(UNAME_P), x86_64)
        ARCH := amd64
    endif
    ifneq ($(filter %86, $(UNAME_P)),)
        ARCH := ia32
    endif
    ifneq ($(filter arm%, $(UNAME_P)),)
        ARCH := arm
    endif
endif

ifeq ($(OS), Windows_NT)
    SYS := windows
else
	ifneq ($(findstring /cygdrive/, $(PATH)),)
		SYS := cygwin
	else
		UNAME := $(shell uname || echo unknown)
		ifeq ($(UNAME), Linux)
			SYS := linux
		endif
		ifeq ($(UNAME), Solaris)
			SYS := solaris
		endif
	endif
endif

toupper		= $(shell $(ECHO) $1 | $(TR) a-z A-Z)
tolower		= $(shell $(ECHO) $1 | $(TR) A-Z a-z)

SYS_DEF 	= MLANG_SYS_$(call toupper, $(SYS))
ARCH_DEF 	= MLANG_ARCH_$(call toupper, $(ARCH))

CPPFLAGS 	= -I"$(SOURCE_PATH)/cpp" -O3 -std=c++11 -finput-charset=UTF-8 -fexec-charset=UTF-8 -D$(SYS_DEF) -D$(ARCH_DEF)
LINKFLAGS	= -s
LIB			= "lib\java\jvm.lib"

BUILD_PATH	= build
SOURCE_PATH = src
PLAT_PATH	= plat
PLAT_DIR	= $(SYS)-$(ARCH)

# 递归的wildcard
rwildcard	= $(foreach D, $(wildcard $(1:=/*)), $(call rwildcard, $D, $2) $(filter $(subst *, %, $2), $D))
src2obj		= $(1:$(SOURCE_PATH)/%.cpp=$(BUILD_PATH)/%.o)

SOURCES 	:= $(call rwildcard, src, *.cpp)
OBJECTS 	:= $(SOURCES:$(SOURCE_PATH)/%.cpp=$(BUILD_PATH)/%.o)
OUTPUT		= main.exe

DIRS 		:= $(sort $(shell $(DIRNAME) $(OBJECTS)))
DIRS 		:= $(sort $(DIRS) $(shell $(DIRNAME) $(DIRS)))
DIRS 		:= $(sort $(DIRS) $(shell $(DIRNAME) $(DIRS)))

include $(SOURCES:.cpp=.d)

.PHONY: all build run mkdir commit clean buildcpp

all: build

build: buildcpp

buildcpp: $(OUTPUT)

run: build
	$(OUTPUT)

$(OUTPUT): $(OBJECTS)
	$(CC) $^ -o $@ $(LIB) $(OFLAGS)

%.d: %.cpp
	$(CC) -MM $(CPPFLAGS) $< -MT $(call src2obj, $<) > $@
	$(ECHO) "	$(CC) -c $< -o $(call src2obj, $<) $(CPPFLAGS)" >> $@

mkdir:
	$(ECHO) $(PLAT_DIR)
	$(MKDIR) $(DIRS)

clean:
	$(RM) $(OBJECTS) $(SOURCES:.cpp=.dep) $(OUTPUT)

# 当前分支
BRANCH		= master
# 提交信息
COMMITMSG	= "update"
# 合并分支时的目标分支
MERGE 		= master

# 一键提交代码
commit:
#	$(GIT) checkout $(BRANCH)
	-$(GIT) add *
	$(GIT) commit -m $(COMMITMSG)
	$(GIT) push -u origin $(BRANCH)
